package com.soledroid;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.StringTokenizer;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SettingsActivity extends Activity {
	SharedPreferences appSettings;
	SharedPreferences.Editor prefEditor; 
	static final String OFFER_PREF = "offerPref";
	static final String TIME_PREF = "timePref";
	static final String IVLE_TOKEN = "ivleToken";
	static final String APP_SETTINGS = "AppSettings";
	static final String MONDAY_LT = "monday_lt";
	static final String TUESDAY_LT = "tuesday_lt";
	static final String WEDNESDAY_LT = "wednesday_lt";
	static final String THURSDAY_LT = "thursday_lt";
	static final String FRIDAY_LT = "friday_lt";
	static final String SATURDAY_LT = "saturday_lt";
	static final String SUNDAY_LT = "sunday_lt";
	static final int IVLE_ACT = 1;
	private CheckBox mOfferNotifView;
	private CheckBox mTimeNotifView;
	private String mDeviceID;
	private PendingIntent pendingIntent;
	private String ivleToken = "";
	private String defaultToken = "261392B8848B44EDC4C37CFF459C2805248EDDF3124879B0AAFCD8A26A2BEB2F0A97F00E87ABB17B4F1E368E41B8C913CB35955F9C8C8FF418E2C72834CDDC3482BFA8E2067C4F1ADADE7BC08A51E954310707782E67E53697B34BC268931F0EDE25C970E61BFF32F04D939260CF40EFDD17677F54BB796C6EE43C77F177824556E0F899AEB4637496250F4C057836DAD0E04BAAA2AC2954389113E6E14032F01DC33CB5B0E661E8CC9739038ACE57774EF6DA3494E829E53028A5AECE4D4644C430EF5B6B07F47B22070DA29831AFB3";
	private Dialog mDialog = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings);
		appSettings = getSharedPreferences(APP_SETTINGS, MODE_PRIVATE);
		
		mDeviceID = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
		
		mOfferNotifView = (CheckBox) findViewById(R.id.pref_check);
		if(appSettings.getBoolean(OFFER_PREF, false)) {
			mOfferNotifView.setChecked(true);
			
			Editor editor = getSharedPreferences(PushService.TAG, MODE_PRIVATE).edit();
	  	  	editor.putString(PushService.PREF_DEVICE_ID, mDeviceID);
	  	  	editor.commit();
	    	
	  	  	PushService.actionStart(getApplicationContext());
	  	  	
		} else {
			mOfferNotifView.setChecked(false);
		}
		
		mOfferNotifView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (((CheckBox) v).isChecked()) {
		            Toast.makeText(getApplicationContext(), "You will receive offer notification", Toast.LENGTH_SHORT).show();
		            prefEditor = appSettings.edit();
		            prefEditor.putBoolean(OFFER_PREF, true);
		            prefEditor.commit();
		            
		            Editor editor = getSharedPreferences(PushService.TAG, MODE_PRIVATE).edit();
			    	editor.putString(PushService.PREF_DEVICE_ID, mDeviceID);
			    	editor.commit();
			    	
			    	PushService.actionStart(getApplicationContext());
				} else {
		            Toast.makeText(getApplicationContext(), "You won't receive offer notification anymore", Toast.LENGTH_SHORT).show();
		            prefEditor = appSettings.edit();
		            prefEditor.putBoolean(OFFER_PREF, false);
		            prefEditor.commit();
		            
		            PushService.actionStop(getApplicationContext());
				}
			}
		});
		
		//lunchtime notif
		mTimeNotifView = (CheckBox) findViewById(R.id.time_check);
		if(appSettings.getBoolean(TIME_PREF, false)) {
			mTimeNotifView.setChecked(true);
			
			//TODO
	  	  	
		} else {
			mTimeNotifView.setChecked(false);
		}
		
		mTimeNotifView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//TODO
				if (((CheckBox) v).isChecked()) {
		            Toast.makeText(getApplicationContext(), "You will receive lunch time notification", Toast.LENGTH_SHORT).show();
		            prefEditor = appSettings.edit();
		            prefEditor.putBoolean(TIME_PREF, true);
		            prefEditor.commit();
		            connectIvle();
		            //processLunchTime();
		            //processAlarm();
				} else {
		            Toast.makeText(getApplicationContext(), "You won't receive lunch time notification anymore", Toast.LENGTH_SHORT).show();
		            prefEditor = appSettings.edit();
		            prefEditor.putBoolean(TIME_PREF, false);
		            prefEditor.commit();
		            
		            killAlarm();
				}
			}
		});
		
		Button lunchTimeBtn = (Button) findViewById(R.id.lt_btn);
		lunchTimeBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mDialog = showTimeTable();
				showDialog(1);
			}
		});
		
		
	}
	protected void onResume() {
    	super.onResume();
    	 //Toast.makeText(getApplicationContext(), "Resumed", Toast.LENGTH_SHORT).show();
    	appSettings = getSharedPreferences(APP_SETTINGS, MODE_PRIVATE);
    	if(appSettings.getBoolean(OFFER_PREF, false)) {
			mOfferNotifView.setChecked(true);
			
			SharedPreferences p = getSharedPreferences(PushService.TAG, MODE_PRIVATE);
	  	  	boolean started = p.getBoolean(PushService.PREF_STARTED, false);
			
	  	  	if(!started) {
	  	  		Editor editor = getSharedPreferences(PushService.TAG, MODE_PRIVATE).edit();
	  	  		editor.putString(PushService.PREF_DEVICE_ID, mDeviceID);
	  	  		editor.commit();
	    	
	  	  		PushService.actionStart(getApplicationContext());
	  	  	}
		} else {
			mOfferNotifView.setChecked(false);
		}
    	
    	if(appSettings.getBoolean(TIME_PREF, false)) {
			mTimeNotifView.setChecked(true);
			
			//TODO
	  	  	
		} else {
			mTimeNotifView.setChecked(false);
			//killAlarm();
		}
	}
	
	protected void processLunchTime() {
		String line = null;

//		try {
			//String token = getToken();
			
			SAXTimeTableParser spe = new SAXTimeTableParser();
			spe.run("https://ivle.nus.edu.sg/api/Lapi.svc/Timetable_Student?APIKey=fCxN5zKDDC8ecZtW2jtpy&AuthToken=" + ivleToken + "&AcadYear=2011/2012&Semester=1");
			//Toast.makeText(getApplicationContext(), spe.getDataString(), Toast.LENGTH_SHORT).show();
			StringTokenizer st = new StringTokenizer(spe.getDataString());
			int[] t = new int[7];
			int i = 0;
		    while (st.hasMoreTokens()) {
		    	t[i] = Integer.parseInt(st.nextToken());
		        i++;
		        //System.out.println(st.nextToken());
		    }
		    prefEditor = appSettings.edit();
	        prefEditor.putInt(MONDAY_LT, t[0]);
	        prefEditor.putInt(TUESDAY_LT, t[1]);
	        prefEditor.putInt(WEDNESDAY_LT, t[2]);
	        prefEditor.putInt(THURSDAY_LT, t[3]);
	        prefEditor.putInt(FRIDAY_LT, t[4]);
	        prefEditor.putInt(SATURDAY_LT, t[5]);
	        prefEditor.putInt(SUNDAY_LT, t[6]);
	        prefEditor.commit();
			

//		} catch (UnsupportedEncodingException e) {
//			line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
//		} catch (MalformedURLException e) {
//			line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
//		} catch (IOException e) {
//			line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
//		}
	
	}
	
	protected void processAlarm() {
		 Intent myIntent = new Intent(this, MyAlarmService.class);
		 pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
		 AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

		 Calendar calendar = Calendar.getInstance();
		 Calendar current = Calendar.getInstance();
		 calendar.set(Calendar.HOUR_OF_DAY, current.get(Calendar.HOUR_OF_DAY) + 1);
		 calendar.set(Calendar.MINUTE, 5);
		 calendar.set(Calendar.SECOND, 0);
		 //alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
		 alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_HOUR, pendingIntent);
		 //Toast.makeText(SettingsActivity.this, "Start Alarm", Toast.LENGTH_LONG).show();
	}
	
	protected void killAlarm() {
		AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
		alarmManager.cancel(pendingIntent);
		this.stopService(new Intent(this, MyAlarmService.class));

		// Tell the user about what we did.
		//Toast.makeText(SettingsActivity.this, "Cancel!", Toast.LENGTH_LONG).show();
	}
	
	protected void connectIvle() {
		Intent i = new Intent(this, AndroidLogin.class);
        
        startActivityForResult(i, IVLE_ACT);
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        switch(requestCode) {
            case IVLE_ACT:
            	appSettings = getSharedPreferences(APP_SETTINGS, MODE_PRIVATE);
            	ivleToken = appSettings.getString(IVLE_TOKEN, "0");
            	if(ivleToken == "0")
            		Toast.makeText(SettingsActivity.this, "You may not get correct IVLE token! Please retry login", Toast.LENGTH_LONG).show();
            	//Toast.makeText(SettingsActivity.this, ivleToken, Toast.LENGTH_LONG).show();
            	processLunchTime();
	            processAlarm();
                break;
        }
    }
//	protected String getToken() {
//		 LayoutInflater factory = LayoutInflater.from(this);            
//	        final View textEntryView = factory.inflate(R.layout.ivlelogin, null);
//	        String token = "";
//	        AlertDialog.Builder alert = new AlertDialog.Builder(this); 
//
//	        alert.setTitle("Please Login to Fogbugz"); 
//	        alert.setMessage("Enter your email and password"); 
//	        // Set an EditText view to get user input  
//	        alert.setView(textEntryView); 
//	        AlertDialog loginPrompt = alert.create();
//
//	        final EditText input1 = (EditText) loginPrompt.findViewById(R.id.ivleuser);
//	        final EditText input2 = (EditText) loginPrompt.findViewById(R.id.ivlepass);
//
//	        alert.setPositiveButton("Login", new DialogInterface.OnClickListener() { 
//	        public void onClick(DialogInterface dialog, int whichButton) { 
//	            input1.getText().toString();
//
//
//	        } 
//	        }); 
//
//	        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
//	          public void onClick(DialogInterface dialog, int whichButton) { 
//	            // Canceled. 
//	          } 
//	        }); 
//
//	        alert.show(); 
//	        
//	        return token;
//	}
	
	public static String MapDay(int day) {
		switch(day) {
		case 1:
			return SUNDAY_LT;
		case 2:
			return MONDAY_LT;
		case 3:
			return TUESDAY_LT;
		case 4:
			return WEDNESDAY_LT;
		case 5:
			return THURSDAY_LT;
		case 6:
			return FRIDAY_LT;
		case 7:
			return SATURDAY_LT;
		default:
				return "";
		}
	}
	
	protected Dialog onCreateDialog(int id) {
	    Dialog dialog;
	    switch(id) {
	    case 1:
	        dialog = mDialog;
	        break;
	    default:
	        dialog = null;
	    }
	    return dialog;
	}
	
	protected Dialog showTimeTable() {
		Context mContext = this;
		Dialog dialog = new Dialog(mContext);
		appSettings = getSharedPreferences(APP_SETTINGS, MODE_PRIVATE);
		dialog.setContentView(R.layout.lunch_time_dialog);
		dialog.setTitle("Your lunch times:");

		TextView monText = (TextView) dialog.findViewById(R.id.mon);
		String aa = "Mon: " + appSettings.getInt(MONDAY_LT, 13);
		monText.setText("Mon: " + appSettings.getInt(MONDAY_LT, 13));
		
		TextView tueText = (TextView) dialog.findViewById(R.id.tue);
		tueText.setText("Tue: " + appSettings.getInt(TUESDAY_LT, 13));
		
		TextView wedText = (TextView) dialog.findViewById(R.id.wed);
		wedText.setText("Wed: " + appSettings.getInt(WEDNESDAY_LT, 13));
		
		TextView thuText = (TextView) dialog.findViewById(R.id.thu);
		thuText.setText("Thu: " + appSettings.getInt(THURSDAY_LT, 13));
		
		TextView friText = (TextView) dialog.findViewById(R.id.fri);
		friText.setText("Fri: " + appSettings.getInt(FRIDAY_LT, 13));
		
		TextView satText = (TextView) dialog.findViewById(R.id.sat);
		satText.setText("Sat: " + appSettings.getInt(SATURDAY_LT, 13));
		
		TextView sunText = (TextView) dialog.findViewById(R.id.sun);
		sunText.setText("Sun: " + appSettings.getInt(SUNDAY_LT, 13));
		
		return dialog;
	}
}
